package com.software.myopiachildren.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.software.myopiachildren.App;
import com.software.myopiachildren.R;
import com.software.myopiachildren.base.BaseFragment;
import com.software.myopiachildren.bean.BaseInfo;
import com.software.myopiachildren.bean.LoginInfo;
import com.software.myopiachildren.bean.UserInfo;
import com.software.myopiachildren.content.Constant;
import com.software.myopiachildren.http.HostType;
import com.software.myopiachildren.http.HttpApi2;
import com.software.myopiachildren.ui.AboutActivity;
import com.software.myopiachildren.ui.BindDeviceActivity;
import com.software.myopiachildren.ui.BluetoothActivity;
import com.software.myopiachildren.ui.CorrectionDistanceActivity;
import com.software.myopiachildren.ui.WarningActivity;
import com.software.myopiachildren.ui.login.LoginActivity;
import com.software.myopiachildren.ui.login.UpdatepwdActivity;
import com.software.myopiachildren.utils.ToastUtil;
import com.software.myopiachildren.utils.eb.EB;
import com.software.myopiachildren.utils.eb.EbData;
import com.software.myopiachildren.utils.perm.NetworkUtils;
import com.software.myopiachildren.utils.sp.SP;
import com.software.myopiachildren.view.dialog.CustomizeDialog;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;

import org.greenrobot.eventbus.Subscribe;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.software.myopiachildren.App.mBluetoothClient;

/**
 * @author penglei
 * @date 2020/04/08
 * 设置
 */
public class SetFragment extends BaseFragment {
    private static final String TAG = "SetFragment";

    @BindView(R.id.iv_title_left)
    ImageView mIvTitleLeft;
    @BindView(R.id.tv_title_text)
    TextView mTvTitleText;
    @BindView(R.id.tv_title_right)
    TextView mTvTitleRight;
    @BindView(R.id.lay_title_home)
    LinearLayout mLayTitleHome;

    @BindView(R.id.tv_username)
    TextView mTvUsername;
    @BindView(R.id.ll_username)
    LinearLayout mLlUsername;
    @BindView(R.id.tv_account)
    TextView mTvAccount;
    @BindView(R.id.ll_account)
    LinearLayout mLlAccount;
    @BindView(R.id.tv_device_status)
    TextView mTvDeviceStatus;
    @BindView(R.id.ll_bind_device)
    LinearLayout mLlBindDevice;
    @BindView(R.id.tv_bluetooth_status)
    TextView mTvBluetoothStatus;
    @BindView(R.id.ll_bluetooth)
    LinearLayout mLlBluetooth;
    @BindView(R.id.tv_distance_status)
    TextView mTvDistanceStatus;
    @BindView(R.id.ll_distance)
    LinearLayout mLlDistance;
    @BindView(R.id.tv_worning_status)
    TextView mTvWorningStatus;
    @BindView(R.id.ll_worning)
    LinearLayout mLlWorning;
    @BindView(R.id.tv_update_pwd)
    TextView mTvUpdatePwd;
    @BindView(R.id.ll_update_pwd)
    LinearLayout mLlUpdatePwd;
    @BindView(R.id.tv_about)
    TextView mTvAbout;
    @BindView(R.id.ll_about)
    LinearLayout mLlAbout;
    @BindView(R.id.tv_version_code)
    TextView mTvVersionCode;
    @BindView(R.id.ll_version_code)
    LinearLayout mLlVersionCode;
    @BindView(R.id.btn_out)
    Button mBtnOut;


    @Override
    protected int getContentViewId() {
        return R.layout.fragment_set;
    }

    @Override
    public void initView() {
        EB.register(this);
        mIvTitleLeft.setVisibility(View.GONE);
        mTvTitleText.setText(getResources().getString(R.string.s_set));
    }

    @Override
    public void initData() {
        getUserInfoData();
        isNewVersion();
    }

    @OnClick({R.id.ll_username, R.id.ll_account, R.id.ll_bind_device, R.id.ll_bluetooth, R.id.ll_distance
            , R.id.ll_worning, R.id.ll_update_pwd, R.id.ll_about, R.id.ll_version_code, R.id.btn_out})
    public void onClick(final View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.ll_username:
                inputNicknameDialog();
                break;

            case R.id.ll_account:

                break;

            case R.id.ll_bind_device:
                intent = new Intent(getActivity(), BindDeviceActivity.class);
                startActivity(intent);
                break;

            case R.id.ll_bluetooth:
                intent = new Intent(getActivity(), BluetoothActivity.class);
                startActivity(intent);
                break;

            case R.id.ll_distance:
                intent = new Intent(getActivity(), CorrectionDistanceActivity.class);
                startActivity(intent);
                break;

            case R.id.ll_worning:
                intent = new Intent(getActivity(), WarningActivity.class);
                startActivity(intent);
                break;

            case R.id.ll_update_pwd:
                intent = new Intent(getActivity(), UpdatepwdActivity.class);
                startActivity(intent);
                break;

            case R.id.ll_about:
                intent = new Intent(getActivity(), AboutActivity.class);
                startActivity(intent);
                break;

            case R.id.ll_version_code:
                Beta.strToastYourAreTheLatestVersion = getResources().getString(R.string.s_version_news);
                //检查更新
                Beta.checkUpgrade();
                break;

            case R.id.btn_out:
                outLoginDialog();
                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        EB.unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void onEvent(EbData data) {
        if (data.getType() == 11) {
            // 设备绑定
            int bind_device = new SP().load(Constant.BIND_DEVICE, 0);
            if (bind_device == 0) {
                mTvDeviceStatus.setText(getResources().getString(R.string.s_unbind));
            } else if (bind_device == 1) {
                mTvDeviceStatus.setText(getResources().getString(R.string.s_onbind));
            }
        } else if (data.getType() == 12) {
            // 检测蓝牙是否打开
            isBluetoothOpened();
        } else if (data.getType() == 13) {
            // 矫正距离
            int corr_dis = new SP().load(Constant.CORR_DIS, 0);
            if (corr_dis == 0) {
                mTvDistanceStatus.setText(getResources().getString(R.string.s_undistance));
            } else {
                mTvDistanceStatus.setText(getResources().getString(R.string.s_ondistance));
            }
        } else if (data.getType() == 31 || data.getType() == 32) {
            // 检测蓝牙是否打开
            isBluetoothOpened();
        } else if (data.getType() == 14) {
            // 预警提示音类型
            getWarningType();
        }

    }


    /**
     * 展示用户信息
     */
    private void getUserInfoData() {
        try {
            // 获取用户信息
            App.user = new Gson().fromJson(new SP().load(Constant.SP_USER_DATA, ""), UserInfo.class);
            if (App.user != null) {
                mTvAccount.setText(App.user.getAccount());
            }

            // 获取用户昵称
            String nickname = new SP().load(Constant.USER_NAME, "");
            if (nickname != null) {
                mTvUsername.setText(nickname);
            }

            // 设备绑定
            int bind_device = new SP().load(Constant.BIND_DEVICE, 0);
            if (bind_device == 0) {
                mTvDeviceStatus.setText(getResources().getString(R.string.s_unbind));
            } else if (bind_device == 1) {
                mTvDeviceStatus.setText(getResources().getString(R.string.s_onbind));
            }

            // 矫正距离
            int corr_dis = new SP().load(Constant.CORR_DIS, 0);
            if (corr_dis == 0) {
                mTvDistanceStatus.setText(getResources().getString(R.string.s_undistance));
            } else {
                mTvDistanceStatus.setText(getResources().getString(R.string.s_ondistance));
            }

            // 检测蓝牙是否打开
            isBluetoothOpened();
            // 预警提示音类型
            getWarningType();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检测蓝牙是否打开
     */
    private void isBluetoothOpened() {
        boolean isBluetoothOpened = mBluetoothClient.isBluetoothOpened();
        if (isBluetoothOpened) {
            mTvBluetoothStatus.setText(getResources().getString(R.string.s_onconnect));
        } else {
            mTvBluetoothStatus.setText(getResources().getString(R.string.s_unconnect));
        }
    }

    /**
     * 预警提示音类型
     */
    private void getWarningType() {
        // 预警提示音
        int warning_type = new SP().load(Constant.WARNING_TYPE, 0);
        if (warning_type == 1) {
            mTvWorningStatus.setText(getResources().getString(R.string.s_warning_content1));
        } else if (warning_type == 2) {
            mTvWorningStatus.setText(getResources().getString(R.string.s_warning_content2));
        }
    }


    /**
     * 检查是否有新版本
     */
    private void isNewVersion(){
        // 判断有没有新版本
        UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();
        if (upgradeInfo == null) {
            mTvVersionCode.setText(getResources().getString(R.string.s_version_code_already));
        } else {
            mTvVersionCode.setText(getResources().getString(R.string.s_version_code_new));
        }
    }


    /**
     * 退出登录弹框
     */
    private void outLoginDialog() {
        final CustomizeDialog dialog = new CustomizeDialog(getActivity(), R.style.DialogUtilStyle);
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);//标题
                TextView tv_cancel = (TextView) dialog.findViewById(R.id.tv_cancel);//取消
                TextView tv_confirm = (TextView) dialog.findViewById(R.id.tv_confirm);//确认

                // 标题
                tv_content.setText(getResources().getString(R.string.s_dia_out));

                //取消
                tv_cancel.setOnClickListener(v -> {
                    dialog.dismiss();
                });

                //确认
                tv_confirm.setOnClickListener(v -> {
                    // 跳转主页面(清除保存在本地的用户信息  token等)
                    App.token = null;
                    App.jwt_token = null;
                    App.user = null;
                    new SP().save(Constant.SP_USER_DATA, "");
                    new SP().save(Constant.USER_ID, "");
                    new SP().save(Constant.USER_NAME, "");
                    new SP().save(Constant.USER_TOKEN, "");
                    new SP().save(Constant.USER_JWT_TOKEN, "");

                    new SP().save(Constant.DEVICE_CODE, "");
                    new SP().save(Constant.BIND_DEVICE, 0);
                    new SP().save(Constant.BLUE_CONN, 0);
                    new SP().save(Constant.CORR_DIS, 0);
                    ToastUtil.showShort(getResources().getString(R.string.s_exit_success));
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    getActivity().finish();
                    dialog.dismiss();
                });
            }
        });
        dialog.showDialog(R.layout.dialog_out);
    }


    /**
     * 修改昵称弹框
     */
    private void inputNicknameDialog() {
        final CustomizeDialog dialog = new CustomizeDialog(getActivity(), R.style.DialogUtilStyle);
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                EditText et_change_nickname_input = (EditText) dialog.findViewById(R.id.et_change_nickname_input);
                Button btn_confirm = (Button) dialog.findViewById(R.id.btn_confirm);
                ImageView iv_close = (ImageView) dialog.findViewById(R.id.iv_close);


                //取消
                iv_close.setOnClickListener(v -> {
                    dialog.dismiss();
                });

                //确认
                btn_confirm.setOnClickListener(v -> {
                    String nickname = et_change_nickname_input.getText().toString().trim();
                    //验证昵称
                    if (TextUtils.isEmpty(nickname)) {
                        ToastUtil.showShort(getString(R.string.toast_nickname_empty));
                        return;
                    }
                    getEditNickname(nickname);
                    dialog.dismiss();
                });
            }
        });
        dialog.showDialog(R.layout.dialog_change_nickname);
    }

    /**
     * 修改昵称
     */
    private void getEditNickname(String nickname) {
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(getActivity())) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("nickname", nickname);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getEditNickname(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                    getUserInfo();
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }


    }

    /**
     * 用户信息
     */
    private void getUserInfo() {
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(getActivity())) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getUserInfo(headers).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<LoginInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(LoginInfo loginInfo) {
                            try {
                                Log.e(TAG, "===loginInfo:" + loginInfo.toString());
                                if (loginInfo.getCode().equals(Constant.CODE_SUCCESS)) {
//                                    App.user = loginInfo.getData(); // 用户参数
//                                    new SP().save(Constant.SP_USER_DATA, new Gson().toJson(loginInfo.getData()));
                                    new SP().save(Constant.USER_NAME, loginInfo.getData().getNickname());

                                    //用户昵称
                                    mTvUsername.setText(loginInfo.getData().getNickname());
                                } else {
                                    ToastUtil.showShort(loginInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }


    }


}
